function G(id) {
    return document.getElementById(id);
}


//创建和初始化地图函数：
function initMap(){
    // createMap();//创建地图
    setMapEvent();//设置地图事件
    addMapControl();//向地图添加控件

    getStrArray();
}

var map = new BMap.Map("l-map");
map.centerAndZoom("广州",12);                   // 初始化地图,设置城市和地图级别。
window.map = map;//将map变量存储在全局
var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
    {"input" : "suggestId"
        ,"location" : map
    });

ac.addEventListener("onhighlight", function(e) {  //鼠标放在下拉列表上的事件
    var str = "";
    var _value = e.fromitem.value;
    var value = "";
    if (e.fromitem.index > -1) {
        value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
    }
    str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

    value = "";
    if (e.toitem.index > -1) {
        _value = e.toitem.value;
        value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
    }
    str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
    G("searchResultPanel").innerHTML = str;
});

var myValue;
//城市 eg广州市
var myCity;
//区 eg天河区
var myDistrict;
//街道 eg 岗顶BRT
var myStreet;

ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件
    var _value = e.item.value;
    myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
    G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
    myStreet = _value.business;
    myCity = _value.city;
    myDistrict = _value.district;
    setPlace();
});

var point = new BMap.Point(116.40384918664363, 39.915446357113886);

/**
 * 定位拖動位置
 * @param xPoint
 * @param yPoint
 */
function  dragendPoint(xPoint,yPoint) {
    //改變地图拖动点
    map.clearOverlays();
    point = new BMap.Point(xPoint, yPoint);

    map.centerAndZoom(point, 14);
    var geoc = new BMap.Geocoder();
    var marker = new BMap.Marker(point);// 创建标注
    map.addOverlay(marker);             // 将标注添加到地图中
    marker.enableDragging();  //设置可拖拽
    marker.addEventListener("dragend", function (e) {  //拖动事件

        var pt = e.point;
        var dizhi;
        geoc.getLocation(pt, function (rs) {

            var addComp = rs.addressComponents;

            dizhi = addComp.city + addComp.district + addComp.street + addComp.streetNumber;

            document.getElementById('suggestId').value = dizhi;//更新地址数据

            var content = dizhi + "<br/><br/>经度：" + e.point.lng + "<br/>纬度：" + e.point.lat;

            var infoWindow = new BMap.InfoWindow("<p style='font-size:14px;'>" + content + "</p>");

            marker.openInfoWindow(infoWindow, map.getCenter());//将经纬度信息显示在提示框内
            $("#xPoint").text(e.point.lng);
            $('#yPoint').text(e.point.lat);

        });
        if (str.length > 0) {
            str[str.length - 1].xPoint = e.point.lng;
            str[str.length - 1].yPoint = e.point.lat;
            pointArray[pointArray.length - 1].lng = e.point.lng;
            pointArray[pointArray.length - 1].lat = e.point.lat;
        }
    });
}



function setPlace(){
    map.clearOverlays();    //清除地图上所有覆盖物
    function myFun(){
        var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
        map.centerAndZoom(pp, 18);
        map.addOverlay(new BMap.Marker(pp));    //添加标注
    }
    var local = new BMap.LocalSearch(map, { //智能搜索
        onSearchComplete: myFun
    });
    local.search(myValue);
    /*https://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding
    * https://api.map.baidu.com/geocoder/v2/?address=北京市海淀区上地十街10号&output=json&ak=您的ak&callback=showLocation
    * */
    $.ajax({
        url : 'https://api.map.baidu.com/geocoder/v2/',
        type : 'GET',
        async:false,
        dataType: 'jsonp',
        jsonp: 'callback',
        jsonpCallback:"showLocation",
        data : {
            address:myValue,
            output:"json",
            ret_coordtype:"bd09ll",
            ak:"gLfdG5Wkt28RFi9IRzGw5M7I8aL155Fq"
        },
        success: function (json) {
            $("#xPoint").text(json.result.location.lng);
            $('#yPoint').text(json.result.location.lat);
            $("#xAddress").text(myValue);
            $("#lng").val(json.result.location.lng);
            $('#lat').val(json.result.location.lat);
            $("#address").val(myValue);
        },
        error: function (xhr, textStatus, errorThrown) {
            //document.write("错误原因"+errorThrown);
        }

    });

}

var str = [];
var pointArray = [];

//创建和初始化地图
initMap();

/**
 * 初始化数据
 */
function getStrArray() {
    var arrayList=[];
    var xPoint=$("#xPoint").text();
    var yPoint=$("#yPoint").text();
    arrayList.push(new BMap.Point(xPoint, yPoint));
   if(arrayList.length>0){
        pointArray = arrayList;
       addPoint()
       //btnClick()
   }
}

/**
 * 添加点到左边地点
 */
function  addPoint() {
    //var xAddress = $("#xAddress").text();
    var xPoint = $("#xPoint").text();
    var yPoint = $("#yPoint").text();
    $("#showResult").show();
    if(xPoint!="" && yPoint!="") {

        //拖动地图的位置
        dragendPoint(xPoint,yPoint);

        //城市和区相同的情况下通过经纬度查询到区
        if(myCity==myDistrict){
           getMyDistrict(xPoint,yPoint,function (rs) {
               myDistrict=rs;
               addPointStep(xPoint,yPoint);
           });
        }else {
            addPointStep(xPoint,yPoint);
        }

    }
}
function addPointStep(xPoint,yPoint) {
    pointArray.push(new BMap.Point(xPoint, yPoint));
}


/**
 * https://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding-abroad
 * https://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=35.658651,139.745415&output=json&pois=1&ak=您的ak
 * @param xPoint
 * @param yPoint
 */
function  getMyDistrict(xPoint,yPoint,callback) {
    //var result ="";
    $.ajax({
        url : 'https://api.map.baidu.com/geocoder/v2/',
        type : 'GET',
        async: false,
        dataType: 'jsonp',
        jsonp: 'callback',
        jsonpCallback:"renderReverse",
        data : {
            location:yPoint+","+xPoint,
            output:"json",
            ak:"gLfdG5Wkt28RFi9IRzGw5M7I8aL155Fq"
        },
        success: function (json) {
            if("function"==typeof(callback)){
                console.log("根据经纬度转换");
                var district = json.result.addressComponent.district;
                console.log(district);
                callback(district);
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            console.log("错误原因"+errorThrown);
        }
    });
}


var icons=new BMap.IconSequence(
    new BMap.Symbol(BMap_Symbol_SHAPE_BACKWARD_OPEN_ARROW,{
        scale: 0.6,
        strokeWeight: 2,
        strokeColor:'#fff'
    }),'10','30');

var _index=0;
function  btnClick() {
    var driving = new BMap.DrivingRoute(map,{
            policy: BMAP_DRIVING_POLICY_LEAST_DISTANCE,
        }
    );

    var pointTwoArray = [];
    for (var i=0;i<pointArray.length;i++) {
        //是否是奇数点
        //是否数组越界
        if(i!=(pointArray.length-1)){
            pointTwoArray.push(pointArray.slice(i,i+2));
        }
    }

    pointTwoArray.forEach(function(value,index){
        _index++;
        driving.search(value[0],value[1]);
    });

    driving.setSearchCompleteCallback(function(){
        var pts = driving.getResults().getPlan(0).getRoute(0).getPath();
        var polyline = new BMap.Polyline(pts, {strokeColor:"green",//设置颜色
            strokeWeight:8, //宽度
            strokeOpacity:0.8,//透明度
            icons:draw_line_direction(8)
            //icons:[icons]
        });
        map.addOverlay(polyline);
        map.centerAndZoom(pts[0],12);
    });
}

function draw_line_direction(weight) {
    var icons=new BMap.IconSequence(
        new BMap.Symbol(BMap_Symbol_SHAPE_BACKWARD_OPEN_ARROW, {
            scale: weight/10,
            strokeWeight: 1,
            rotation: 0,
            fillColor: 'white',
            fillOpacity: 1,
            strokeColor:'white'
        }),'100%','5%',false);
    return icons;
}

//地图事件设置函数：
function setMapEvent(){
    map.enableDragging();//启用地图拖拽事件，默认启用(可不写)
    map.enableScrollWheelZoom();//启用地图滚轮放大缩小
    map.enableDoubleClickZoom();//启用鼠标双击放大，默认启用(可不写)
    map.enableKeyboard();//启用键盘上下左右键移动地图
}

//地图控件添加函数：
function addMapControl(){
    //向地图中添加缩放控件
    var ctrl_nav = new BMap.NavigationControl({anchor:BMAP_ANCHOR_TOP_LEFT,type:BMAP_NAVIGATION_CONTROL_LARGE});
    map.addControl(ctrl_nav);
    //向地图中添加缩略图控件
    var ctrl_ove = new BMap.OverviewMapControl({anchor:BMAP_ANCHOR_BOTTOM_RIGHT,isOpen:1});
    map.addControl(ctrl_ove);
    //向地图中添加比例尺控件
    var ctrl_sca = new BMap.ScaleControl({anchor:BMAP_ANCHOR_BOTTOM_LEFT});
    map.addControl(ctrl_sca);
}